from datetime import timedelta, datetime
import wtforms
from flask import request
from flask_wtf import FlaskForm
from wtforms.validators import Email, Length, EqualTo
from models import UserModel, EmailCaptchaModel, ImageCaptchaModel
from wtforms import StringField, PasswordField, validators
from wtforms.validators import DataRequired, Length, Email, EqualTo

from exts import db


# Form: 主要就是用来验证前端提交的数据是否符合要求
class RegisterForm(wtforms.Form):
    email = wtforms.StringField(validators=[Email(message="邮箱格式错误！")])
    captcha = wtforms.StringField(validators=[Length(min=6, max=6, message="验证码格式错误！")])
    username = wtforms.StringField(validators=[Length(min=3, max=20, message="用户名格式错误！")])
    password = wtforms.StringField(validators=[Length(min=8, max=16, message="密码格式错误！")])
    password_confirm = wtforms.StringField(validators=[EqualTo("password", message="两次密码不一致！")])

    # 自定义验证:
    # 1.邮箱是否已经被注册
    def validate_email(self, field):
        email = field.data
        user = UserModel.query.filter_by(email=email).first()
        if user:
            raise wtforms.ValidationError(message="该邮箱已经被注册！")

    # 2.验证码是否正确
    def validate_captcha(self, field):
        captcha = field.data
        email = self.email.data
        captcha_model = EmailCaptchaModel.query.filter_by(email=email, captcha=captcha).first()

        if not captcha_model:
            raise wtforms.ValidationError(message="邮箱或验证码错误！")

        # 检查验证码是否过期（5分钟有效期）
        expiration_time = captcha_model.created_time + timedelta(minutes=5)
        if datetime.now() > expiration_time:
            db.session.delete(captcha_model)
            db.session.commit()
            raise wtforms.ValidationError(message="验证码已过期，请重新获取！")


class LoginForm(wtforms.Form):
    email = wtforms.StringField(validators=[Email(message="邮箱格式错误！")])
    password = wtforms.StringField(validators=[Length(min=8, max=16, message="密码格式错误！")])


class UpdateProfileForm(FlaskForm):
    username = StringField('用户名', validators=[
        DataRequired(message='请输入用户名'),
        Length(min=3, max=20, message='用户名长度3-20个字符')
    ])
    email = StringField('邮箱', validators=[
        DataRequired(message='请输入邮箱'),
        Email(message='邮箱格式不正确')
    ])
    first_name = StringField('名字', validators=[
        Length(max=20, message='名字长度不超过20个字符')
    ])
    last_name = StringField('姓氏', validators=[
        Length(max=20, message='姓氏长度不超过20个字符')
    ])
    address = StringField('地址', validators=[
        Length(max=100, message='地址长度不超过100个字符')
    ])
    city = StringField('城市', validators=[
        Length(max=50, message='城市长度不超过50个字符')
    ])
    country = StringField('国家', validators=[
        Length(max=50, message='国家长度不超过50个字符')
    ])
    postal_code = StringField('邮政编码', validators=[
        Length(max=20, message='邮政编码长度不超过20个字符')
    ])
    bio = StringField('个人简介', validators=[
        Length(max=500, message='个人简介长度不超过500个字符')
    ])


class ChangePasswordForm(FlaskForm):
    current_password = PasswordField('当前密码', validators=[
        DataRequired(message='请输入当前密码')
    ])
    new_password = PasswordField('新密码', validators=[
        DataRequired(message='请输入新密码'),
        Length(min=8, message='密码长度至少8位')
    ])
    confirm_password = PasswordField('确认新密码', validators=[
        DataRequired(message='请确认新密码'),
        EqualTo('new_password', message='两次输入的密码不一致')
    ])
